package com.xmb.wcapi.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xmb.wcapi.annotation.ValidateJWT;
import com.xmb.wcapi.constant.*;
import com.xmb.wcapi.dto.*;
import com.xmb.wcapi.entity.*;
import com.xmb.wcapi.service.*;
import com.xmb.wcapi.util.Column;
import com.xmb.wcapi.util.DateUtil;
import com.xmb.wcapi.util.ExcelTool;
import com.xmb.wcapi.util.TitleEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/wc_api")
public class ForeignApiController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ForeignApiService foreignApiService;

    @Autowired
    private IIOSReportService reportService;

    @Autowired
    private IQualityDataService dataService;

    @Autowired
    private IBaseMaterialService baseMaterialService;

    @Autowired
    private IOptionApiDataService optionApiDataService;

    @Value("${startTime}")
    private String startTime;

    /**
     * 获取token
     * @return
     */
    @GetMapping("/getToken")
    @ResponseBody
    public Map<String, Object> getToken(String code, String pwd){
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(pwd)){
            return Dict.create().set("statusCode",500).set("message","Failed").set("data",null);
        }
        //没有登录
        //获取企业信息
        String string = DigestUtil.md5Hex(pwd);
        Customer one = customerService.getOne(Wrappers.lambdaQuery(Customer.class)
                .eq(Customer::getCusCode,code)
                .eq(Customer::getPwd,string)
        );
        if (null != one){
            //存在企业  设定2小时过期
            String token = IdUtil.simpleUUID();
            redisTemplate.opsForValue().set("cusCode",code);
            redisTemplate.opsForValue().set("api:" + token, code, 2,TimeUnit.HOURS);
            Map<String,String> map = new HashMap<>();
            map.put("msg","token的有效期为2小时");
            map.put("token",token);
            return Dict.create().set("statusCode",200).set("message","Success").set("data",map);
        }
        return Dict.create().set("statusCode",500).set("message","Failed").set("data",null);
    }

    /**
     * 获取库存
     * @return
     */
    @PostMapping("/getInventoryAgoNextApi")
    @ResponseBody
    @ValidateJWT
    public Map<String, Object> getInventoryAgoNextApi(String cusCode,String material,String invDef){
        LayTableR inventoryAgoNext = foreignApiService.getInventoryAgoNext(cusCode, material,invDef);
        if (null != inventoryAgoNext.get("count")){
            List<BaseMaterial> data = (List<BaseMaterial>) inventoryAgoNext.get("data");
            List<InventoryDTO> inventoryDTOS = new ArrayList<>();
            for (BaseMaterial datum : data) {
                long l = datum.getSum().longValue();
                InventoryDTO dto = new InventoryDTO();
                dto.setImg01(datum.getDjMaterial());
                dto.setIma021(datum.getCusMaterial());
                dto.setIma02(datum.getMaterialMrk());
                dto.setImg02(datum.getClassName());
                dto.setImg03("");
                dto.setImg04("");
                dto.setImg10(String.valueOf(l < 0?0:l));
                inventoryDTOS.add(dto);
            }
            inventoryAgoNext.put("data",inventoryDTOS);
            return Dict.create().set("statusCode",200).set("message","Success").set("data",inventoryDTOS);
        }else {
            return Dict.create().set("statusCode",200).set("message","Success").set("data",null);
        }
//        return inventoryAgoNext;
//        return Dict.create().set("statusCode",200).set("message","Success").set("data",null);
    }

    /**
     * 对比前数据
     * @return
     */
    @GetMapping("/inventoryAgoHtml")
    public String inventoryAgoHtml(){
        return "inventoryAgo/index";
    }
    /**
     * 获取 对比前数据
     * @return
     */
    @PostMapping("/getInventoryAgo")
    @ResponseBody
    public LayTableR getInventoryAgo(Integer page,Integer limit,String cusCode,String material,String invDef){
        return foreignApiService.getInventoryAgo(page, limit, cusCode, material,invDef);
    }

    /**
     * 对比后数据
     * @return
     */
    @GetMapping("/inventoryNextHtml")
    public String inventoryNextHtml(){
        return "inventoryNext/index";
    }
    /**
     * 获取 对比后数据
     * @return
     */
    @PostMapping("/getInventoryAgoNext")
    @ResponseBody
    public LayTableR getInventoryAgoNext(String cusCode,String material,String invDef){
        return foreignApiService.getInventoryAgoNext(cusCode, material,invDef);
    }

    /**
     * 获取 对比前数据
     * @return
     */
    @GetMapping("/getInventoryDow")
    @ResponseBody
    public void getInventoryDow(String str,String cusCode,String material,String invDef,HttpServletResponse response){
        String queryCriteriaStr = "【查询条件】 供应商编码：" + cusCode + "；料号：" + material+ "；机种：" + invDef;
        List<TitleEntity> titleList=new ArrayList<>();
        titleList.add(new TitleEntity("0",null,"调整"+str+"库存管理信息表",null));
        titleList.add(new TitleEntity("1","0",queryCriteriaStr,null));

        titleList.add(new TitleEntity("2","1","⼚商料号","djMaterial"));
        titleList.add(new TitleEntity("3","1","纬创料号或制程","cusMaterial"));
        titleList.add(new TitleEntity("4","1","品名或料号描述","materialMrk"));
        titleList.add(new TitleEntity("5","1","仓库","className"));
        titleList.add(new TitleEntity("6","1","储位","storageSpace"));
        titleList.add(new TitleEntity("7","1","批号(批次号)","batchNumber"));
        titleList.add(new TitleEntity("8","1","数量","sum"));

        //查询数据
        List<Object> list = new ArrayList<>();
        if (str.equals("前")){
            list = (List<Object>) foreignApiService.getInventoryAgo(-1, -1, cusCode, material,invDef).get("data");
        }else {
            list = (List<Object>) foreignApiService.getInventoryAgoNext(cusCode, material,invDef).get("data");
        }
        if (null == list){
            list = new ArrayList<>();
        }
        try {
            ExcelTool excelTool = new ExcelTool("库存管理信息表",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("调整"+str+"库存管理信息表"+ DateUtil.currentYYMMDD()+".xlsx", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 人力接口
     * @return
     */
    @PostMapping("/getDutyAgoNextApi")
    @ResponseBody
    @ValidateJWT
    public Map<String, Object> getDutyAgoNextApi(){
        String startTime = DateUtil.getDateFormat(cn.hutool.core.date.DateUtil.lastWeek());
        String endTime = DateUtil.getDateFormat(new Date());
//        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
//            return Dict.create().set("statusCode",500).set("message","Success").set("data",null);
//        }
//        if (startTime.compareTo(startTime) < 0 || endTime.compareTo(startTime) < 0){
//            return Dict.create().set("statusCode",500).set("message","Failed").set("data",null);
//        }
        LayTableR agoNext = foreignApiService.getDutyAgoNext(-1, -1, startTime,endTime);
        if (null != agoNext.get("count")){
            List<DutyAgo> data = (List<DutyAgo>) agoNext.get("data");
            List<ManpowerDTO> manp = new ArrayList<>();
            for (DutyAgo datum : data) {
                ManpowerDTO dto = new ManpowerDTO();
                dto.setClockInDate(datum.getCardTime());
                dto.setVendorCode("620425");
                dto.setManufacturer("DONGJU");
                dto.setDayShiftTotalNumber(String.valueOf(datum.getDaytimeSum()));
                dto.setDayShiftDLNumber(String.valueOf(datum.getDaytimeDLSum()));
                dto.setDayShiftIDLNumber(String.valueOf(datum.getDaytimeIDLSum()));
                dto.setNightShiftTotalNumber(String.valueOf(datum.getNightSum()));
                dto.setNightShiftDLNumber(String.valueOf(datum.getNightDLSum()));
                dto.setNightShiftIDLNumber(String.valueOf(datum.getNightIDLSum()));
                dto.setEmployeesTotalNumber(String.valueOf(datum.getDutySum()));
                dto.setEmployeesDLNumber(String.valueOf(datum.getDutyDLSum()));
                dto.setEmployeesIDLNumber(String.valueOf(datum.getDutyIDLSum()));
                dto.setUploadDate(DateUtil.getDateTimeFormat(new Date()));
                manp.add(dto);
            }
            agoNext.put("data",manp);
        }else {
            agoNext.put("data",null);
        }
        return Dict.create().set("statusCode",200).set("message","Success").set("data",agoNext.get("data"));
    }


    @GetMapping("/getDutyAgoHtml")
    public String getDutyAgoHtml(){
        return "dutyAgo/index";
    }
    /**
     * 人力调整前
     * 获取 对比前数据
     * @return 查询远程门禁实时数据
     */
    @PostMapping("/getDutyAgo")
    @ResponseBody
    public LayTableR getDutyAgo(Integer page,Integer limit,String startTime,String endTime){
        return foreignApiService.getDutyAgo(page, limit, startTime,endTime);
    }

    @GetMapping("/getDutyAgoNextHtml")
    public String getDutyAgoNextHtml(){
        return "dutyAgoNext/index";
    }
    /**
     * 人力调整后
     * 获取 对比后数据
     * @return 如果本地有，查询本地，没有就查询远程后添加到本地
     */
    @PostMapping("/getDutyAgoNext")
    @ResponseBody
    public LayTableR getDutyAgoNext(Integer page,Integer limit,String startTime,String endTime){
        return foreignApiService.getDutyAgoNext(page, limit, startTime,endTime);
    }

    @PostMapping("/getDutyAgoNext/reload")
    @ResponseBody
    public R reload(String startTime, String endTime){
        return foreignApiService.invReload(startTime, endTime);
    }

    @RequestMapping("/getDutyDow")
    @ResponseBody
    public void getDutyDow(String str,String startTime,String endTime, HttpServletResponse response) {

        String queryCriteriaStr = "【查询条件】 开始时间：" + startTime + "；结束时间：" + endTime;
        List<TitleEntity> titleList=new ArrayList<>();
        titleList.add(new TitleEntity("0",null,"调整"+str+"供应商人力管理信息表",null));
        titleList.add(new TitleEntity("1","0",queryCriteriaStr,null));

        titleList.add(new TitleEntity("2","1","厂商","manufacturer"));
        titleList.add(new TitleEntity("3","1","Vendor Code","vendorCode"));
        titleList.add(new TitleEntity("4","1","打卡日期","cardTime"));
        titleList.add(new TitleEntity("5","1","在职人数","dutySum"));
        titleList.add(new TitleEntity("6","1","在职直接人数","dutyDLSum"));
        titleList.add(new TitleEntity("7","1","在职间接人数","dutyIDLSum"));
        titleList.add(new TitleEntity("8","1","白班直接人数","daytimeDLSum"));
        titleList.add(new TitleEntity("9","1","白班间接人数","daytimeIDLSum"));
        titleList.add(new TitleEntity("10","1","白班总人数","daytimeSum"));
        titleList.add(new TitleEntity("11","1","夜班直接人数","nightDLSum"));
        titleList.add(new TitleEntity("12","1","夜班间接人数","nightIDLSum"));
        titleList.add(new TitleEntity("12","1","夜班总人数","nightSum"));
        titleList.add(new TitleEntity("12","1","当日总人数","daySum"));

        //查询数据
        List<Object> list = new ArrayList<>();
        if (str.equals("前")){
            list = (List<Object>) foreignApiService.getDutyAgo(1, 500, startTime,endTime).get("data");
        }else {
            list = (List<Object>) foreignApiService.getDutyAgoNext(1, 500, startTime,endTime).get("data");
        }
        if (null == list){
            list = new ArrayList<>();
        }
        try {
            ExcelTool excelTool = new ExcelTool("生产流转信息表",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("调整"+str+"供应商人力管理信息表"+ DateUtil.currentYYMMDD()+".xlsx", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * bom
     * @return
     */
    @GetMapping("/getIOSReportHtml")
    public String getIOSReportHtml(){
        return "report/index";
    }
    @GetMapping("/getIOSReport")
    @ResponseBody
    public Object getIOSReport(Integer page,Integer limit,String cusCode,String material,String cInvDefine9){
        if (StringUtils.isEmpty(cusCode) || StringUtils.isEmpty(material)){
            return LayTableR.result(0,0,"供应商编码和母件编码是必须的！");
        }
        IPage<IOSReportDetails> iPage = reportService.selectInfoTreePage(cusCode, material,cInvDefine9);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 0);
        resultMap.put("msg", "ok");
        resultMap.put("data", iPage.getRecords());
        resultMap.put("count", iPage.getTotal());
        return resultMap;
    }

    @GetMapping("/getIOSReportHtmlNext")
    public String getIOSReportHtmlNext(){
        return "reportNext/index";
    }
    @GetMapping("/getIOSReportNext")
    @ResponseBody
    public Object getIOSReportNext(Integer page,Integer limit,String cusCode,String material,String cInvDefine9){
        if (StringUtils.isEmpty(cusCode) || StringUtils.isEmpty(material)){
            return LayTableR.result(0,0,"供应商编码和母件编码是必须的！");
        }
        IPage<IOSReportDetails> iPage = reportService.selectInfoTreePage(cusCode, material,cInvDefine9);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 0);
        resultMap.put("msg", "ok");
        resultMap.put("data", iPage.getRecords());
        resultMap.put("count", iPage.getTotal());
        return resultMap;
    }

    /**
     * Api Bom接口
     */
    @PostMapping("/getIOSReportApi")
    @ResponseBody
    @ValidateJWT
    public Map<String, Object> getIOSReportApi(String cusCode){
        if (StringUtils.isEmpty(cusCode)){
            Boolean b = redisTemplate.hasKey("cusCode");
            if (b){
                cusCode = Objects.requireNonNull(redisTemplate.opsForValue().get("cusCode")).toString();
            }
        }
        List<ApiBomVo> list = reportService.selectAllDom(cusCode);
        return Dict.create().set("statusCode",200).set("message","Success").set("data",list);
    }


    @GetMapping("/qualityDataIndex")
    public String qualityDataIndex(){
        return "qualityData/index";
    }

    @GetMapping("/qualityDataIndexNext")
    public String qualityDataIndexNext(){
        return "qualityDataNext/index";
    }

    @PostMapping("/qualityData")
    @ResponseBody
    public LayTableR qualityData(Integer page,Integer limit,String cusCode,String startTime,String endTime,String material){
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
            return LayTableR.result(0,0,null);
        }
        IPage<QualityData> list =  dataService.qualityData(page,limit,cusCode,startTime,endTime,material);
        for (QualityData record : list.getRecords()) {
            if(StringUtils.isNotEmpty(record.getStrDepartmentName())){
                record.setStrDepartmentName(record.getStrDepartmentName().replace("课",""));
            }
        }
        return LayTableR.result(0,list.getTotal(),list.getRecords());
    }

    @PostMapping("/qualityDataNext")
    @ResponseBody
    public LayTableR qualityDataNext(Integer page,Integer limit,String cusCode,String startTime,String endTime,String material){
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
            return LayTableR.result(0,0,null);
        }
        IPage<QualityData> list =  dataService.qualityDataNext(-1,-1,cusCode,startTime,endTime,material);
        return LayTableR.result(0,list.getTotal(),list.getRecords());
    }

    /**
     * 良率接口
     */
    @PostMapping("/qualifiedApi")
    @ResponseBody
    @ValidateJWT
    public Map<String, Object> qualifiedApi(@RequestBody JSONObject jsonObject){
        String startDate = jsonObject.getStr("startDate");
        String endDate = jsonObject.getStr("endDate");
        //如果没有传递日期就自己决定
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)){
            return Dict.create().set("statusCode",500).set("message","Failed").set("data",null);
        }
        long between = cn.hutool.core.date.DateUtil.between(new Date(),DateUtil.getDateFormat(endDate), DateUnit.DAY);
        if (between <= 0){
            return Dict.create().set("statusCode",500).set("message","Failed").set("data",null);
        }
        String dataKey = "qualifiedApi" + startDate;
        //获取缓存数据是否存在
//        Boolean aBoolean = redisTemplate.hasKey(dataKey);
//        if (Boolean.TRUE.equals(aBoolean)){
//            List range = redisTemplate.opsForList().range(dataKey, 0, -1);
//            return Dict.create().set("statusCode",200).set("message","Success").set("data",range.get(2));
//        }
        String cusCode = null;
        Boolean b = redisTemplate.hasKey("cusCode");
        if (b){
            cusCode = Objects.requireNonNull(redisTemplate.opsForValue().get("cusCode")).toString();
        }
        Customer one = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getCusCode, cusCode));
        IPage<QualityData> list =  dataService.qualityDataNextApi(-1,-1,cusCode,startDate,endDate,null);
        Set<String> collect = list.getRecords().stream().map(QualityData::getMaterial).collect(Collectors.toSet());
        List<BaseMaterial> list1 = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class).in(BaseMaterial::getDjMaterial, collect));
        list1 = list1.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BaseMaterial::getBomId))), ArrayList::new)
        );
        Map<String, BaseMaterial> collect1 = list1.stream().collect(Collectors.toMap(BaseMaterial::getDjMaterial, obj -> obj));
        List<QualifiedDTO> allList = new ArrayList<>();
        for (QualityData record : list.getRecords()) {
            //查询每天待处理
            OptionApiData optionApiData = optionApiDataService.getOne(Wrappers.lambdaQuery(OptionApiData.class).eq(OptionApiData::getTime, record.getTimes()));
            BaseMaterial baseMaterial = collect1.get(record.getMaterial());
            //查询自己所属 顶级bom
            List<BaseMaterial> list2 = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class).eq(BaseMaterial::getBomId, baseMaterial.getAllComponentId()));
            QualifiedDTO dto = new QualifiedDTO();
            dto.setAreaCode(one.getCsdm());
            dto.setCustomerName(one.getCusName());
            dto.setCustomerCode(one.getKhdm());
            dto.setWorkTime(record.getTimes());
            dto.setZhiCheng(record.getStrDepartmentName());
            dto.setTour(record.getTour());
            dto.setMachineName(record.getDeviceName());
            dto.setMachineType(baseMaterial.getTypeOfMachine());
            String spec =  SpecConstant.Others.getMessage();
            //如果包含指定的
            for (SpecConstant value : SpecConstant.values()) {
                if (baseMaterial.getMaterialMrk().contains(value.getCode())){
                    spec = value.getMessage();
                    break;
                }
            }
            dto.setOrderNo(baseMaterial.getCusMaterial());
            dto.setSpec(spec);
            if (list2 != null && !list2.isEmpty()) {
                BaseMaterial baseMaterial1 = list2.get(0);
                dto.setPartnum(baseMaterial1.getDjMaterial());
                //如果OrderNo为空就用顶级bom纬创料号
                if (StringUtils.isEmpty(dto.getOrderNo())){
                    dto.setOrderNo(baseMaterial1.getCusMaterial());
                }
            }else {
                dto.setPartnum(baseMaterial.getDjMaterial());
            }
            dto.setStandardNum(String.valueOf(record.getNonDefective().setScale(2,BigDecimal.ROUND_DOWN).doubleValue()));
            dto.setSecondStandardNum(String.valueOf(record.getNonDefective().setScale(2,BigDecimal.ROUND_DOWN).doubleValue()));
            dto.setDefectiveNum(String.valueOf(record.getDefectiveProducts().setScale(3,BigDecimal.ROUND_DOWN).doubleValue()));
            BigDecimal bigDecimal = new BigDecimal(record.getPercentage()).divide(BigDecimal.valueOf(100)).setScale(3, RoundingMode.DOWN);
//            dto.setDefectiveRate(String.valueOf(BigDecimal.valueOf(1).subtract(bigDecimal).setScale(3,BigDecimal.ROUND_DOWN).doubleValue()));
            //二次良率与良率同步
            dto.setDefectiveRate(String.valueOf(bigDecimal.doubleValue()));

            //如果有不良品数
            if (null != record.getDefectiveProducts()){
                //获取不良品数量
                int count = record.getDefectiveProducts().intValue();
                if (count > 0){
                    //调整不良原因
                    if (StringUtils.isEmpty(record.getPoorDistribution())){
                        Map<String, List<String>> listMap = getDict();
                        List<String> stringList = new ArrayList<>();
                        int tally = 0;
                        for (String key : listMap.keySet()) {
                            //如果包含指定的
                            if (baseMaterial.getMaterialMrk().contains(key)){
                                List<String> strings = listMap.get(key);
                                //计算每个不良品原因的数量
                                List<Integer> randomSplits = randomSplit(count, strings.size());
                                for (int i = 0; i < strings.size(); i++) {
                                    stringList.add(strings.get(i) + "(" + randomSplits.get(i) + ")");
                                }
                                break;
                            }else {
                                tally++;
                            }
                        }
                        if (tally == listMap.size()){
                            dto.setDefectiveReasonName("Other"+"(" + count + ")");
                        }
                        if (!stringList.isEmpty()){
                            dto.setDefectiveReasonName(String.join(",",stringList));
                        }
                    }else {
                        //截取不良原因
                        String[] split = record.getPoorDistribution().split(",");
                        //计算每个不良品原因的数量
                        List<String> errStrList = new ArrayList<>();
                        List<Integer> randomSplits = randomSplit(count, split.length);
                        for (int i = 0; i < split.length; i++) {
                            String str = split[i];
                            errStrList.add(str.substring(0,str.indexOf("("))+ "(" + randomSplits.get(i) + ")");
                        }
                        dto.setDefectiveReasonName(String.join(",",errStrList));
                    }
                }
            }

            if (null != optionApiData){
                dto.setOption1(optionApiData.getOption1());
                dto.setOption2(optionApiData.getOption2());
                dto.setOption3(optionApiData.getOption3());
            }
//            dto.setAuditDate(DateUtil.getDateTimeFormat(new Date()));
            dto.setAuditDate(record.getStateTime());
            dto.setProcessYieldGoal(String.valueOf(bigDecimal.doubleValue()));
            //如果是其他就不返回给接口
            if (!spec.equals(SpecConstant.Others.getMessage())){
                allList.add(dto);
            }
        }
//        redisTemplate.opsForList().leftPushAll(dataKey, allList, 24,TimeUnit.HOURS);
//        return LayTableR.result(0,allList.size(),allList);
        return Dict.create().set("statusCode",200).set("message","Success").set("data",allList);
    }

    public static List<Integer> randomSplit(int total, int parts) {
        List<Integer> result = new ArrayList<>();
        Random random = new Random();
        int remaining = total;

        // 先为每个部分分配1
        for (int i = 0; i < parts; i++) {
            result.add(1);
            remaining--;
        }

        // 随机分配剩余的数
        for (int i = 0; i < parts - 1; i++) {
            // 确保最小能分到1，最多分配remaining - (parts - i - 1)以保证后续部分至少为1
            int max = remaining - (parts - i - 1);
            if (max <= 0) break; // 如果没有剩余，则退出循环
            int split = random.nextInt(max) + 1; // 最少分配1
            result.set(i, result.get(i) + split);  // 添加随机值
            remaining -= split;
        }

        // 最后的部分值为剩余的
        result.set(parts - 1, result.get(parts - 1) + remaining);
        return result;
    }

    @RequestMapping("qualityData/download")
    @ResponseBody
    public void download(String str,String cusCode,String startTime,String endTime,String material, HttpServletResponse response) {

        String queryCriteriaStr = "【查询条件】 开始时间：" + startTime + "；结束时间：" + endTime + "；供应商编码："+cusCode;
        List<TitleEntity> titleList=new ArrayList<>();
        titleList.add(new TitleEntity("0",null,"调整"+str+"生产流转信息表",null));
        titleList.add(new TitleEntity("1","0",queryCriteriaStr,null));

        titleList.add(new TitleEntity("13","1","单号","lngWorkLoadNo"));
        titleList.add(new TitleEntity("14","1","预计起始","times"));
        titleList.add(new TitleEntity("4","1","⼚商料号","material"));
        titleList.add(new TitleEntity("2","1","纬创料号或制程","strDepartmentName"));
        titleList.add(new TitleEntity("3","1","品名或料号描述","strGoodsName"));
        titleList.add(new TitleEntity("6","1","投入数","invest"));
        titleList.add(new TitleEntity("7","1","待处理数","pending"));
        titleList.add(new TitleEntity("8","1","累计待处理数","pendingCumulative"));
        titleList.add(new TitleEntity("9","1","良品数","nonDefective"));
        titleList.add(new TitleEntity("10","1","不良品数","defectiveProducts"));
        titleList.add(new TitleEntity("11","1","不良分布","poorDistribution"));
        titleList.add(new TitleEntity("12","1","良率","percentage"));
        //查询数据
        List<QualityData> list = null;
        if (str.equals("前")){
           list = dataService.qualityData(-1, -1, cusCode, startTime, endTime, material).getRecords();
        }else {
            list = dataService.qualityDataNext(-1, -1, cusCode, startTime, endTime, material).getRecords();
        }
        if (null == list){
            list = new ArrayList<>();
        }
        try {
            ExcelTool excelTool = new ExcelTool("调整"+str+"生产流转信息表",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("调整"+str+"生产流转信息表"+ DateUtil.currentYYMMDD()+".xlsx", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/qualityDataApi")
    @ResponseBody
    @ValidateJWT
    public Map<String, Object> qualityDataApi(){
        //开始时间是上周
        String startTime = DateUtil.getDateFormat(cn.hutool.core.date.DateUtil.lastWeek());
        String endTime = DateUtil.getDateFormat(new Date());
        String cusCode = null;
//        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
//            return LayTableR.result(0,0,null);
//        }
//        if (startTime.compareTo(startTime) < 0 || endTime.compareTo(startTime) < 0){
//            return LayTableR.result(0,0,null);
//        }
//        if (StringUtils.isEmpty(cusCode)){
            Boolean b = redisTemplate.hasKey("cusCode");
            if (b){
                cusCode = Objects.requireNonNull(redisTemplate.opsForValue().get("cusCode")).toString();
            }
//        }
        IPage<QualityData> list =  dataService.qualityDataNext(-1,-1,cusCode,startTime, endTime, null);
        List<WipDTO> dtos = new ArrayList<>();
        for (QualityData record : list.getRecords()) {
            WipDTO dto = new WipDTO();
            dto.setSfb01(record.getLngWorkLoadNo());
            if (StringUtils.isNotEmpty(record.getTimes())){
                dto.setSfb13(record.getTimes());
            }
            dto.setSfb05(record.getMaterial());
            boolean mark = true;
            for (DepConstant value : DepConstant.values()) {
                if (record.getStrGoodsName().contains(value.getMessage())){
                    dto.setIma021(value.getMessage());
                    mark = false;
                }
            }
            if (mark){
                dto.setIma021(record.getCusMaterial());
            }
            dto.setIma02(record.getStrGoodsName());
            dto.setSfb08(record.getPlanSum().toString());
            dto.setSfb081(record.getPlanSum().toString());
            dto.setSfb09(record.getNonDefective().toString());
            dto.setSfb102("");
            dto.setSfbud02("");
            dto.setWoType("Production");
            dto.setSfb091(record.getDefectiveProducts().toString());
            dtos.add(dto);
        }
//        return LayTableR.result(0,dtos.size(),dtos);
        return Dict.create().set("statusCode",200).set("message","Success").set("data",dtos);
    }

    /**
     * 获取自定义不良原因
     */
    private Map<String, List<String>> getDict(){
        Map<String, List<String>> dict = new HashMap<>();
        dict.put("冲压", Arrays.asList("压伤"));
        dict.put("CNC", Arrays.asList("压伤","CNC不良"));
        dict.put("打磨", Arrays.asList("碰划伤","打磨不良"));
        dict.put("喷砂", Arrays.asList("碰划伤","喷砂不良"));
        dict.put("阳极", Arrays.asList("碰划伤","异色","阳极不良"));
        dict.put("镭雕", Arrays.asList("碰划伤"));
        dict.put("热压组装", Arrays.asList("碰划伤","溢胶","热压不良"));
        return dict;
    }

}
